package com.gxa.insurance.exceptionHandler;

import com.gxa.insurance.exception.BusinessException;
import com.gxa.insurance.exception.ExceptionCode;
import com.gxa.insurance.util.JsonResult;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author Min
 */
@RestController
@ControllerAdvice
public class ExceptionController {

    /**
     * 可以根据异常类型自动选择进入不同的方法
     * @return
     */
//    @ExceptionHandler(Exception.class)
//    public Map ExceptionHandler(){
//
//    }
    /**
     * 亦可以选择将所有异常集中处理
     *  异常的信息是用过声明参数的方式，让SpringMVC自动注入
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public Map businessExceptionHandler(Exception e){
        JsonResult jsonResult = new JsonResult();
        if(e instanceof BusinessException){
            BusinessException be=(BusinessException)e;
            jsonResult.setCode(be.getExceptionCode().getCode());
            jsonResult.setMsg(be.getExceptionCode().getMessage());
            return jsonResult.getMap();
        }else {
            jsonResult.setMsg(ExceptionCode.SERVER_FAILED.getMessage());
            jsonResult.setCode(ExceptionCode.SERVER_FAILED.getCode());
            return jsonResult.getMap();
        }
    }

}
